#!/bin/bash

################################################################################
# 精子银行管理系统 - 快速更新脚本
# Sperm Bank Management System - Quick Update Script
#
# 功能：快速更新前端（不重启后端，不重置数据库）
#
# 使用方法：
#   chmod +x update.sh
#   ./update.sh
#
################################################################################

set -e  # 遇到错误立即退出

# ========== 颜色定义 ==========
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# ========== 配置 ==========
PROJECT_DIR="/var/www/sperm-bank_-db"
FRONTEND_DIR="$PROJECT_DIR/frontend"

# ========== 工具函数 ==========
print_header() {
    echo -e "\n${BLUE}========================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}========================================${NC}\n"
}

print_success() { echo -e "${GREEN}✓ $1${NC}"; }
print_error() { echo -e "${RED}✗ $1${NC}"; }
print_warning() { echo -e "${YELLOW}⚠ $1${NC}"; }

# ========== 开始更新 ==========
clear
echo -e "${GREEN}"
echo "╔════════════════════════════════════════════════════════╗"
echo "║            精子银行系统 - 快速更新前端                 ║"
echo "╚════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# 1. 切换到项目目录
print_header "[1/4] 切换到项目目录"
cd "$PROJECT_DIR" || {
    print_error "无法切换到项目目录: $PROJECT_DIR"
    exit 1
}
print_success "当前目录: $(pwd)"

# 2. 拉取最新代码
print_header "[2/4] 拉取最新代码"
if git pull origin master; then
    print_success "代码更新成功"
else
    print_error "代码更新失败"
    exit 1
fi

# 3. 安装依赖（如果 package.json 有变化）
print_header "[3/4] 检查并更新依赖"
cd "$FRONTEND_DIR" || {
    print_error "无法切换到前端目录: $FRONTEND_DIR"
    exit 1
}
if npm install; then
    print_success "依赖检查完成"
else
    print_warning "依赖安装失败，继续构建..."
fi

# 4. 构建前端
print_header "[4/4] 构建前端"
if npm run build; then
    print_success "前端构建成功"
else
    print_error "前端构建失败"
    exit 1
fi

# 完成
echo -e "\n${GREEN}╔════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║              ✓ 前端更新完成！                          ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════════════════╝${NC}\n"

echo -e "${YELLOW}下一步操作：${NC}"
echo "  1. 在浏览器中按 ${YELLOW}Ctrl+Shift+Delete${NC} 清除缓存"
echo "  2. 或按 ${YELLOW}F12${NC} -> Network -> Disable cache"
echo "  3. 刷新页面 (${YELLOW}F5${NC})"
echo ""

